package net.mohas.docsearch.controller;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import net.mohas.docsearch.model.db.SqliteDatabase;


/**
 *
 * @author Muhammad
 */
public class DatabaseOperation {
    
    protected Connection connection;
    
    private String table;
    private ResultSet resultSet;

    public DatabaseOperation() {
        SqliteDatabase db = SqliteDatabase.getInstance();
		connection = db.getConnection();
    }

    public String getTabel() {
        return table;
    }

    public void setTabel(String tabel) {
        this.table = tabel;
    }

    public void hapusTabel(String namatabel) throws Exception {
        System.out.println("Menghapus tabel " + namatabel + "...");
        setTabel(namatabel);
        PreparedStatement query = connection.prepareStatement("TRUNCATE TABLE " + table);
        query.executeUpdate();
        query.close();
    }

    public void hapusSemuaTabel() throws Exception {
        hapusTabel("berkas");
        hapusTabel("kata");
        hapusTabel("df");
        hapusTabel("kueri");
    }

    public ResultSet sqlSelect(String sql) throws Exception {
        PreparedStatement query = connection.prepareStatement(sql);
        resultSet = query.executeQuery();
        return resultSet;
    }

    public void sqlUpdate(String sql) throws Exception {
        PreparedStatement query = connection.prepareStatement(sql);
        query.executeUpdate();
        query.close();
    }

    public int getJumlahRecord(String namatabel) throws Exception{
        setTabel(namatabel);
        ResultSet result = sqlSelect("SELECT * FROM " + table);
        int i = 0;
        while (result.next()){
            i++;
        }
        return i;
    }
}
